from fastapi import APIRouter, HTTPException
from typing import Dict, Any

from ..core.models import ChatMessage, ActionRequest, MessageResponse
from ..core.state import MESSAGES, ORDERS, push_message
from ..services.catalog import list_products
from ..services.flow import handle_user_select_product, handle_sales_confirm_to_supplier, handle_supplier_ship
from ..services.ai_adapter import detect_intent_and_candidates


router = APIRouter()


@router.get("/health")
def health():
	return {"status": "ok"}


@router.get("/products")
def products():
	return {"items": list_products()}


@router.get("/messages")
def get_messages(role: str):
	return {"items": MESSAGES.get(role, [])}


@router.get("/orders")
def list_orders():
	return {"items": list(ORDERS.values())}


@router.post("/chat", response_model=MessageResponse)
def chat(msg: ChatMessage):
	push_message(msg.role, "text", msg.content)

	if msg.role == "user":
		intent = detect_intent_and_candidates(msg.content)
		if intent["intent"] == "query_product":
			options = [
				{"label": f"{p['name']} | {p['summary']} | ￥{p['price']}", "value": p["productId"]}
				for p in intent["products"]
			]
			return push_message(
				"user",
				"form",
				"为你找到商品，请选择要下单的型号：",
				{"formType": "selectProduct", "options": options, "submitAction": "user_select_product"}
			)
		if intent["intent"] == "order_by_natural" and intent.get("selectedProductId"):
			return handle_user_select_product(intent["selectedProductId"])
		return push_message("user", "text", "我可以帮你选型、下单与通知销售，你可以先说需求~")

	if msg.role == "sales":
		text = msg.content
		if "确认" in text or "可以下单" in text or "直接下给供应商" in text:
			return handle_sales_confirm_to_supplier()
		return push_message("sales", "text", "若同意直接下给供应商，请回复“确认”或点击按钮。")

	if msg.role == "supplier":
		text = msg.content
		if any(k in text for k in ["单号", "快递", "物流"]):
			from uuid import uuid4
			return handle_supplier_ship(company="顺丰速运", tracking_no="SF" + uuid4().hex[:10].upper())
		return push_message("supplier", "text", "请回复快递公司与单号，例如：顺丰，单号SF1234567890。")

	raise HTTPException(status_code=400, detail="未知角色或未识别的消息")


@router.post("/action", response_model=MessageResponse)
def action(req: ActionRequest):
	if req.action == "user_select_product":
		pid = (req.params or {}).get("productId")
		if not pid:
			raise HTTPException(status_code=400, detail="缺少productId")
		return handle_user_select_product(pid)

	if req.action == "sales_confirm_to_supplier":
		return handle_sales_confirm_to_supplier()

	if req.action == "supplier_submit_shipment":
		company = (req.params or {}).get("company")
		tracking_no = (req.params or {}).get("trackingNo")
		if not company or not tracking_no:
			raise HTTPException(status_code=400, detail="缺少快递信息")
		return handle_supplier_ship(company=company, tracking_no=tracking_no)

	raise HTTPException(status_code=400, detail="未知动作")


